<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="论坛名称" prop="forumName">
        <el-input
            v-model="queryParams.forumName"
            placeholder="请输入论坛名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="发布人ID" prop="userId">
              <el-input
                v-model="queryParams.userId"
                placeholder="请输入发布人ID"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>-->
      <el-form-item label="发布人" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入发布人名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="浏览次数" prop="pageViews">
              <el-input
                v-model="queryParams.pageViews"
                placeholder="请输入浏览次数"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="点赞数量" prop="likeCount">
              <el-input
                v-model="queryParams.likeCount"
                placeholder="请输入点赞数量"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="论坛类别" prop="category.categoryname">
              <el-input
                v-model="queryParams['category.categoryname']"
                placeholder="请输入论坛类别"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>-->
      <el-form-item label="论坛类别" prop="category.categoryname">
        <el-select
            v-model="queryParams['category.categoryname']"
            placeholder="请选择论坛类别"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
        >
          <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.categoryname"
              :value="item.categoryname"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['community:posts:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['community:posts:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['community:posts:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['community:posts:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="论坛名称" align="center" prop="forumName" />
      <el-table-column label="论坛内容" show-overflow-tooltip align="center" prop="forumContent" />
      <el-table-column label="论坛图片" align="center" prop="contentImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.contentImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="发布人ID" align="center" prop="userId" />-->
      <el-table-column label="发布人名称" align="center" prop="userName" />
      <el-table-column label="浏览次数" align="center" prop="pageViews" />
      <el-table-column label="点赞数量" align="center" prop="likeCount" />
      <!--      <el-table-column label="论坛类别" align="center" prop="categoryId" />-->
      <el-table-column label="论坛类别" align="center" prop="category.categoryname" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!--v-hasPermi="['community:posts:edit']"-->
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['community:posts:view']">查看</el-button>
          <el-button link type="primary" icon="Edit"  v-if=flagBtn>修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['community:posts:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改论坛管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="postsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="论坛名称" prop="forumName">
          <el-input v-model="form.forumName" placeholder="请输入论坛名称" />
        </el-form-item>
        <el-form-item label="论坛内容" prop="forumContent">
          <el-input v-model="form.forumContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="论坛图片" prop="contentImage">
          <image-upload v-model="form.contentImage"/>
        </el-form-item>
        <!--        <el-form-item label="发布人ID" prop="userId">
                  <el-input v-model="form.userId" placeholder="请输入发布人ID" />
                </el-form-item>-->
        <el-form-item label="发布人" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入发布人名称" :readonly="flag"/>
        </el-form-item>
        <!--        <el-form-item label="论坛类别" prop="categoryId">
                  <el-input v-model="form.categoryId" placeholder="请输入论坛类别" />
                </el-form-item>-->
        <el-form-item label="论坛类别" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择论坛类别" clearable>
            <el-option
                v-for="item in categoryData"
                :label="item.categoryname"
                :value="item.id"
                :key="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="浏览次数" prop="pageViews" v-show="flagFrom">
          <el-input readonly v-model="form.pageViews" placeholder="请输入浏览次数" />
        </el-form-item>
        <el-form-item label="点赞数量" prop="likeCount" v-show="flagFrom">
          <el-input readonly v-model="form.likeCount" placeholder="请输入点赞数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Posts">
import { listPosts, getPosts, delPosts, addPosts, updatePosts } from "@/api/community/posts"

const { proxy } = getCurrentInstance()

const postsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    forumName: null,
    forumContent: null,
    contentImage: null,
    userId: null,
    userName: null,
    pageViews: null,
    likeCount: null,
    categoryId: null,
    category: {
      id: null,
      categoryname: null
    }
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/*#region  -------------二次开发------------------*/

import { listCategory } from "@/api/community/category";
import { getUser } from "@/api/system/user.js";
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user' // 引入用户仓库（若依Pinia）
import { useRouter } from "vue-router";
const router = useRouter()

const userStore = useUserStore()

//论坛类型存储
const categoryData = ref([])
/*查询论坛表类型*/
function getCategoryList(){
  listCategory().then(response => {
    categoryData.value = response
  })
  /*.catch(error => {
    ElMessage.error('论坛类别获取失败')
  })*/
}
/*控制文本框是否只读*/
const flag = ref(false)
/*控制表单显示隐藏*/
const flagFrom = ref(false)
/*控制查看按钮显示隐藏：用户可以查看详情，管理员看不了，只能进行crud*/
const getUserType = () => {
  getUser(userStore.id).then(response => {
    const roles = response.roles
    for (let i = 0; i < roles.length; i++) {
      if (roles[i].roleId === 1){
        flagBtn.value = true //后续需要改为false，现在是为了方便测试
        return
      }
    }
  })
}


/*查看按钮：点击跳转到详情页面*/
/*function handleView(row) {
  const _id = row.id || ids.value
  getPosts(_id).then(response => {
    router.push(`/forumDetails/${_id}`)
  })
}*/
// posts/index.vue 中的 handleView 函数
function handleView(row) {
  const _id = row?.id
  // 使用 push 而不是 replace，这样可以使用 back() 返回
  router.push({ path: `/community/posts/forumDetails/${_id}` })
}

/*#endregion */

/** 查询论坛管理列表 */
function getList() {
  loading.value = true
  listPosts(queryParams.value).then(response => {
    postsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    forumName: null,
    forumContent: null,
    contentImage: null,
    userId: null,
    userName: null,
    createTime: null,
    pageViews: null,
    likeCount: null,
    categoryId: null
  }
  // 如果希望每次重置后也带上当前用户，可在这里同步填充
  if (userStore.id) {
    form.value.userId = userStore.id
    form.value.userName = userStore.nickName
  }
  proxy.resetForm("postsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  flag.value = true
  flagFrom.value = false
  // 确保已加载用户信息（首次进入极小概率未加载）
  if (!userStore.id) {
    // 若在路由守卫中已加载，一般不会走到这里
    userStore.getInfo().then(() => {
      form.value.userId = userStore.id
      form.value.userName = userStore.nickName // 若后台字段是 userName，用昵称赋值展示
      open.value = true
      title.value = "添加论坛管理"
    })
    return
  }
  // 正常直接从store取
  form.value.userId = userStore.id
  form.value.userName = userStore.nickName
  open.value = true
  title.value = "添加论坛管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPosts(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改论坛管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePosts(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPosts(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除论坛管理编号为"' + _ids + '"的数据项？').then(function() {
    return delPosts(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('community/posts/export', {
    ...queryParams.value
  }, `posts_${new Date().getTime()}.xlsx`)
}

getUserType()
getCategoryList()  // 页面加载时获取分类数据
getList()
</script>